<template>
  <div>

    <div v-model="searchData" style="margin: 10px 0">
      <el-input v-model="searchData.name" style="width: 200px" placeholder="请输入书名"
                suffix-icon="el-icon-search"></el-input>
      <el-input v-model="searchData.author" style="width: 200px" placeholder="请输入作者" suffix-icon="el-icon-message"
                class="ml-5"></el-input>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="rest">重置</el-button>
      <el-button v-if="user.role!=='管理员'" type="primary" @click="$router.push('/front/home')">去前台页面</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button v-if="user.role==='管理员'|| user.role ==='教师'" type="primary" @click="addHander">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
      <el-button v-if="user.role==='管理员'|| user.role ==='教师'" type="danger" @click="delBatch">批量删除 <i class="el-icon-remove-outline"></i></el-button>
    </div>

    <el-table :data="tableData" border stripe :header-cell-class-name="headerBg" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55"></el-table-column>-->
      <el-table-column prop="id" label="Id" width="40"></el-table-column>
      <el-table-column prop="name" label="书名" width="120"></el-table-column>
      <el-table-column  label="图片" style="align-content: center">
        <template slot-scope="scope">
          <el-popover
              placement="right"
              title=""
              trigger="hover"
          >
            <!-- 放大的图片 -->
            <el-image style= "max-height: 10rem; max-width: 13rem;height: 50%" :src="scope.row.url" />
            <!-- 表格中的图片 -->
            <el-image style="align-content: center;max-width: 7rem;max-height: 6rem"  slot="reference" :src="scope.row.url"></el-image>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="author" label="作者" width="100"></el-table-column>
      <el-table-column prop="score" label="评分" width="100">
        <template slot-scope="scope">
        {{scope.row.score ? scope.row.score:'暂无评分'}}
        </template>
      </el-table-column>
      <el-table-column prop="bookSort" label="分类" width="100"></el-table-column>
      <el-table-column prop="num" label="库存" width="100"></el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="description" label="描述"></el-table-column>
      <el-table-column prop="createTime" label="出版日期"  width="180"></el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-button type="primary" v-if="user.role==='学生'" :disabled="scope.row.num===0" @click="borrow(scope.row.id)">借阅 <i class="el-icon-reading"></i></el-button>
          <el-button v-if="user.role==='管理员'|| user.role ==='教师'" type="success" @click="handleEdit(scope.row.id)">编辑 <i class="el-icon-edit"></i></el-button>
          <el-button v-if="user.role==='管理员'|| user.role ==='教师'" type="danger" @click="del(scope.row.id)">删除 <i class="el-icon-remove-outline"></i></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog title="新增书籍" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="form" label-width="80px" size="small">
        <el-form-item label="书名">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="form.sortId" placeholder="请选择" style="width: 100%">
            <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="form.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
              action="http://localhost:9090/book/upload"
              :show-file-list="false"
              :on-success="uploadsuccess"
              style="display: inline-block">
            <el-button type="primary" class="ml-5" style="align-content: center">选择图片</el-button>
          </el-upload>
          <el-image v-if="form.url" :src="form.url" class="ml-5" style="width: 30%;height: 30%"></el-image>
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="form.num" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版日期" style="width: 100%">
          <el-date-picker
              style="width: 100%"
              v-model="form.createTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改书籍信息" :visible.sync="updateFormVisible" width="30%">
      <el-form :model="info" label-width="80px" size="small">
        <el-form-item label="书名">
          <el-input v-model="info.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="info.sortId" placeholder="请选择" style="width: 100%">
            <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="info.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
              action="http://localhost:9090/book/upload"
              :show-file-list="false"
              :on-success="uploadsuccess"
              style="display: inline-block">
            <el-button type="primary" class="ml-5" style="align-content: center">选择图片</el-button>
          </el-upload>
          <el-image v-if="info.url" :src="info.url" class="ml-5" style="width: 30%;height: 30%"></el-image>
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="info.num" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="info.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="update">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Book",
  data(){
    return{
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : '' ,
      multipleSelection: [],
      searchData: {
        name: '',
        author: '',
      },
      form: {
        url: ''
      },
      info:{
        url: ''
      },
      tableData: [],
      headerBg: 'headerBg',
      current: 0,
      total: 0,
      pageSize: 10,
      dialogFormVisible: false,
      updateFormVisible: false,
      options:[],
      status:'',

    }
  },
  created() {
    this.load()
  },
  methods:{
    uploadsuccess(res){
      console.log('上传成功后的')
      console.log(res)
      this.form.url = res
      this.info.url = res
    },
    borrow(id){
        this.request.post("/book/borrow/"+ id +"/"+ this.user.id).then(res=>{
          if (res.code===200){
             this.$message.success("借阅申请提交成功")
            this.load()
          }
        })
    },
    handleSelectionChange(val){
      this.multipleSelection=val
      console.log(this.multipleSelection.map(v=>v.id))
    },
    delBatch(){
      let ids =  this.multipleSelection.map(v=>v.id)  //[1,2,3]
      this.$confirm('此操作将删除这些用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.delete("/book/delete/batch/"+ids).then(resp=>{
          if (resp.data){
            this.load()
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    del(id){
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.delete("/book/delete/"+id).then(resp=>{
          if (resp.code===200){
            this.load()
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    addHander() {
      this.dialogFormVisible = true
      this.form = {}

      //获得角色下拉的选项
      this.request.get("/book").then(res=>{
        console.log(res)
        this.options = res.data
      })
    },

    rest() { //重置搜索栏
      this.searchData.username = ''
      this.searchData.email = ''
      this.searchData.address = ''
      this.load()
    },
    handleSizeChange(pageSize) {
      console.log("每页条数: " + pageSize)
      this.pageSize = pageSize;
      this.load()
    },
    handleCurrentChange(current) {
      console.log("当前页码: " + current)
      this.current = current;
      this.load()
    },
    collapse() {  // 点击收缩按钮触发
      this.isCollapse = !this.isCollapse
      if (this.isCollapse) {  // 收缩
        this.sideWidth = 64
        this.collapseBtnClass = 'el-icon-s-unfold'
        this.logoTextShow = false
      } else {   // 展开
        this.sideWidth = 200
        this.collapseBtnClass = 'el-icon-s-fold'
        this.logoTextShow = true
      }
    },
    load() {
      this.request.get("/book/page", {
            params: {
              current: this.current,
              pageSize: this.pageSize,
              name: this.searchData.name,
              author: this.searchData.author
            }
          }
      ).then(resp => {
        console.log(resp)
        this.tableData = resp.data.records
        this.total = resp.data.total

        console.log(2645615165)
        console.log(this.status)

      })
    },
    save() {//新增用户
      this.request.post("/book/save", this.form).then(resp => {
        console.log('this form')
        console.log(this.form)
        console.log(resp)
        if (resp.data) {
          this.$message.success("保存成功")
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("保存失败")
          this.load()
        }
      })
    },
    //编辑
    handleEdit(id) {
      console.log(id)
      this.request.get("/book/"+id).then(resp=>{
        console.log("根据id查到的数据")
        console.log(resp)
        this.info=resp.data
      })
      //获得角色下拉的选项
      this.request.get("/book").then(res=>{
        this.options = res.data
      })
      this.updateFormVisible = true

    },
    //更新数据
    update() {
      this.request.put("/book/update/",this.info).then(resp=>{
        if (resp.data) {
          this.$message.success("更新成功")
          this.updateFormVisible = false
          this.load()
        } else {
          this.$message.error("更新失败")
        }
      })
    }
  }
}
</script>

<style>
.headerBg {
  background: #eee !important;
}
.el-tooltip__popper{
  max-width:20%;
}
.el-tooltip__popper,.el-tooltip__popper.is-dark{
  background:rgb(48, 65, 86) !important;
  color: #fff !important;
  line-height: 24px;
}
</style>